#!/usr/bin/env python3
"""
修复版检测区域可视化工具
确保显示正确的正方形检测区域
"""

import pyautogui
import tkinter as tk
from tkinter import ttk, messagebox
import time
from utils.dominant_color_detector import DominantColorDetector

class FixedDetectionAreaVisualizer:
    """修复版检测区域可视化器"""
    
    def __init__(self):
        self.root = tk.Tk()
        self.root.title("颜色检测区域可视化 (修复版)")
        self.root.geometry("700x600")
        self.root.attributes('-topmost', True)
        
        # 检测器
        self.detector = None
        self.overlay_window = None
        
        self.setup_ui()
        
    def setup_ui(self):
        """设置UI界面"""
        # 主框架
        main_frame = ttk.Frame(self.root, padding="10")
        main_frame.grid(row=0, column=0, sticky=(tk.W, tk.E, tk.N, tk.S))
        
        # 标题
        title_label = ttk.Label(main_frame, text="颜色检测区域可视化 (修复版)", font=("Arial", 16, "bold"))
        title_label.grid(row=0, column=0, columnspan=2, pady=(0, 20))
        
        # 参数设置区域
        params_frame = ttk.LabelFrame(main_frame, text="检测参数", padding="10")
        params_frame.grid(row=1, column=0, columnspan=2, sticky=(tk.W, tk.E), pady=(0, 10))
        
        # 区域大小设置
        ttk.Label(params_frame, text="检测区域大小:").grid(row=0, column=0, sticky=tk.W)
        self.region_size_var = tk.StringVar(value="200")
        region_size_combo = ttk.Combobox(params_frame, textvariable=self.region_size_var, 
                                       values=["50", "100", "150", "200", "250", "300"], width=10)
        region_size_combo.grid(row=0, column=1, padx=(5, 0))
        ttk.Label(params_frame, text="像素 (正方形)").grid(row=0, column=2, padx=(5, 0))
        
        # 聚类数量设置
        ttk.Label(params_frame, text="K-Means聚类数:").grid(row=1, column=0, sticky=tk.W, pady=(5, 0))
        self.clusters_var = tk.StringVar(value="3")
        clusters_combo = ttk.Combobox(params_frame, textvariable=self.clusters_var,
                                    values=["2", "3", "4", "5"], width=10)
        clusters_combo.grid(row=1, column=1, padx=(5, 0), pady=(5, 0))
        
        # 信息显示区域
        info_frame = ttk.LabelFrame(main_frame, text="屏幕和区域信息", padding="10")
        info_frame.grid(row=2, column=0, columnspan=2, sticky=(tk.W, tk.E), pady=(0, 10))
        
        # 屏幕尺寸
        screen_width, screen_height = pyautogui.size()
        screen_info = f"屏幕尺寸: {screen_width} x {screen_height} 像素"
        ttk.Label(info_frame, text=screen_info).grid(row=0, column=0, sticky=tk.W)
        
        # 屏幕中心
        center_x, center_y = screen_width // 2, screen_height // 2
        center_info = f"屏幕中心: ({center_x}, {center_y})"
        ttk.Label(info_frame, text=center_info).grid(row=1, column=0, sticky=tk.W)
        
        # 检测区域信息
        self.area_info_label = ttk.Label(info_frame, text="")
        self.area_info_label.grid(row=2, column=0, sticky=tk.W)
        
        # 像素信息
        self.pixel_info_label = ttk.Label(info_frame, text="")
        self.pixel_info_label.grid(row=3, column=0, sticky=tk.W)
        
        # 当前颜色信息
        self.color_info_label = ttk.Label(info_frame, text="")
        self.color_info_label.grid(row=4, column=0, sticky=tk.W)
        
        # 详细颜色信息
        self.detail_info_label = ttk.Label(info_frame, text="")
        self.detail_info_label.grid(row=5, column=0, sticky=tk.W)
        
        # 按钮区域
        button_frame = ttk.Frame(main_frame)
        button_frame.grid(row=3, column=0, columnspan=2, pady=(10, 0))
        
        # 显示检测区域按钮
        self.show_area_btn = ttk.Button(button_frame, text="显示正方形检测区域", command=self.show_detection_area)
        self.show_area_btn.grid(row=0, column=0, padx=(0, 10))
        
        # 显示无边框区域按钮
        self.show_borderless_btn = ttk.Button(button_frame, text="显示无边框区域", command=self.show_borderless_area)
        self.show_borderless_btn.grid(row=0, column=1, padx=(0, 10))
        
        # 隐藏检测区域按钮
        self.hide_area_btn = ttk.Button(button_frame, text="隐藏检测区域", command=self.hide_detection_area)
        self.hide_area_btn.grid(row=0, column=2, padx=(0, 10))
        
        # 实时检测按钮
        self.start_detection_btn = ttk.Button(button_frame, text="开始实时检测", command=self.start_real_time_detection)
        self.start_detection_btn.grid(row=1, column=0, padx=(0, 10), pady=(5, 0))
        
        # 停止检测按钮
        self.stop_detection_btn = ttk.Button(button_frame, text="停止检测", command=self.stop_real_time_detection)
        self.stop_detection_btn.grid(row=1, column=1, pady=(5, 0))
        
        # 验证按钮
        self.verify_btn = ttk.Button(button_frame, text="验证正方形", command=self.verify_square)
        self.verify_btn.grid(row=1, column=2, padx=(10, 0), pady=(5, 0))
        
        # 实时检测状态
        self.detecting = False
        
        # 更新区域信息
        self.update_area_info()
        
        # 绑定参数变化事件
        region_size_combo.bind('<<ComboboxSelected>>', lambda e: self.update_area_info())
        clusters_combo.bind('<<ComboboxSelected>>', lambda e: self.update_area_info())
    
    def update_area_info(self):
        """更新区域信息显示"""
        try:
            region_size = int(self.region_size_var.get())
            screen_width, screen_height = pyautogui.size()
            center_x, center_y = screen_width // 2, screen_height // 2
            
            # 计算检测区域边界
            half_size = region_size // 2
            left = center_x - half_size
            top = center_y - half_size
            right = center_x + half_size
            bottom = center_y + half_size
            
            # 验证是否为正方形
            width = right - left
            height = bottom - top
            is_square = width == height == region_size
            
            area_info = f"检测区域: ({left}, {top}) 到 ({right}, {bottom})"
            self.area_info_label.config(text=area_info)
            
            # 计算像素数量和形状验证
            pixel_count = region_size * region_size
            shape_info = f"形状: {width}x{height} 像素 ({'✅正方形' if is_square else '❌非正方形'}), 总像素: {pixel_count:,}"
            self.pixel_info_label.config(text=shape_info)
                
        except ValueError:
            self.area_info_label.config(text="无效的区域大小")
            self.pixel_info_label.config(text="")
    
    def show_detection_area(self):
        """显示检测区域覆盖层（带边框）"""
        try:
            region_size = int(self.region_size_var.get())
            screen_width, screen_height = pyautogui.size()
            center_x, center_y = screen_width // 2, screen_height // 2
            
            # 计算检测区域边界
            half_size = region_size // 2
            left = center_x - half_size
            top = center_y - half_size
            
            # 隐藏现有窗口
            self.hide_detection_area()
            
            # 创建覆盖层窗口
            self.overlay_window = tk.Toplevel()
            self.overlay_window.title(f"检测区域 {region_size}x{region_size}")
            self.overlay_window.geometry(f"{region_size}x{region_size}+{left}+{top}")
            self.overlay_window.attributes('-topmost', True)
            self.overlay_window.attributes('-alpha', 0.4)  # 半透明
            self.overlay_window.configure(bg='red')
            
            # 添加信息标签
            info_text = f"检测区域\n{region_size}x{region_size}\n正方形"
            label = tk.Label(self.overlay_window, text=info_text, 
                           bg='red', fg='white', font=("Arial", 10, "bold"))
            label.pack(expand=True)
            
            # 添加边框验证
            canvas = tk.Canvas(self.overlay_window, bg='red', highlightthickness=0)
            canvas.pack(fill='both', expand=True)
            
            # 绘制边框线条验证正方形
            canvas.create_rectangle(2, 2, region_size-2, region_size-2, outline='yellow', width=2)
            canvas.create_line(2, 2, region_size-2, region_size-2, fill='yellow', width=1)  # 对角线
            canvas.create_line(region_size-2, 2, 2, region_size-2, fill='yellow', width=1)  # 对角线
            
            # 10秒后自动隐藏
            self.root.after(10000, self.hide_detection_area)
            
            print(f"显示检测区域: {region_size}x{region_size} 在位置 ({left}, {top})")
            
        except ValueError:
            messagebox.showerror("错误", "无效的区域大小")
    
    def show_borderless_area(self):
        """显示无边框检测区域"""
        try:
            region_size = int(self.region_size_var.get())
            screen_width, screen_height = pyautogui.size()
            center_x, center_y = screen_width // 2, screen_height // 2
            
            # 计算检测区域边界
            half_size = region_size // 2
            left = center_x - half_size
            top = center_y - half_size
            
            # 隐藏现有窗口
            self.hide_detection_area()
            
            # 创建无边框覆盖层窗口
            self.overlay_window = tk.Toplevel()
            self.overlay_window.overrideredirect(True)  # 无边框
            self.overlay_window.geometry(f"{region_size}x{region_size}+{left}+{top}")
            self.overlay_window.attributes('-topmost', True)
            self.overlay_window.attributes('-alpha', 0.3)
            self.overlay_window.configure(bg='blue')
            
            # 创建画布验证正方形
            canvas = tk.Canvas(self.overlay_window, bg='blue', highlightthickness=0, 
                             width=region_size, height=region_size)
            canvas.pack()
            
            # 绘制网格验证正方形
            grid_size = region_size // 10
            for i in range(0, region_size, grid_size):
                canvas.create_line(i, 0, i, region_size, fill='white', width=1)
                canvas.create_line(0, i, region_size, i, fill='white', width=1)
            
            # 绘制中心十字
            canvas.create_line(region_size//2, 0, region_size//2, region_size, fill='yellow', width=2)
            canvas.create_line(0, region_size//2, region_size, region_size//2, fill='yellow', width=2)
            
            # 绘制边框
            canvas.create_rectangle(0, 0, region_size-1, region_size-1, outline='red', width=3)
            
            # 添加尺寸标注
            canvas.create_text(region_size//2, 15, text=f"{region_size}px", fill='white', font=("Arial", 8, "bold"))
            canvas.create_text(15, region_size//2, text=f"{region_size}px", fill='white', font=("Arial", 8, "bold"), angle=90)
            
            # 8秒后自动隐藏
            self.root.after(8000, self.hide_detection_area)
            
            print(f"显示无边框检测区域: {region_size}x{region_size} 在位置 ({left}, {top})")
            
        except ValueError:
            messagebox.showerror("错误", "无效的区域大小")
    
    def verify_square(self):
        """验证检测区域是否为正方形"""
        try:
            region_size = int(self.region_size_var.get())
            screen_width, screen_height = pyautogui.size()
            center_x, center_y = screen_width // 2, screen_height // 2
            
            # 计算检测区域边界
            half_size = region_size // 2
            left = center_x - half_size
            top = center_y - half_size
            right = center_x + half_size
            bottom = center_y + half_size
            
            # 验证计算
            width = right - left
            height = bottom - top
            
            verification_text = f"""
检测区域验证报告:
==================
设置大小: {region_size}x{region_size}
屏幕中心: ({center_x}, {center_y})
半径: {half_size}

计算边界:
  左边界: {center_x} - {half_size} = {left}
  右边界: {center_x} + {half_size} = {right}
  上边界: {center_y} - {half_size} = {top}
  下边界: {center_y} + {half_size} = {bottom}

实际尺寸:
  宽度: {right} - {left} = {width}
  高度: {bottom} - {top} = {height}

验证结果: {'✅ 正方形' if width == height == region_size else '❌ 非正方形'}
"""
            
            messagebox.showinfo("正方形验证", verification_text)
            
        except ValueError:
            messagebox.showerror("错误", "无效的区域大小")
    
    def hide_detection_area(self):
        """隐藏检测区域覆盖层"""
        if self.overlay_window:
            self.overlay_window.destroy()
            self.overlay_window = None
    
    def start_real_time_detection(self):
        """开始实时检测"""
        try:
            region_size = int(self.region_size_var.get())
            k_clusters = int(self.clusters_var.get())
            
            # 创建检测器
            self.detector = DominantColorDetector(
                region_size=region_size,
                k_clusters=k_clusters,
                cache_duration=0.01
            )
            
            self.detecting = True
            self.start_detection_btn.config(state='disabled')
            self.stop_detection_btn.config(state='normal')
            
            # 开始检测循环
            self.detection_loop()
            
        except ValueError:
            messagebox.showerror("错误", "无效的参数")
    
    def stop_real_time_detection(self):
        """停止实时检测"""
        self.detecting = False
        self.start_detection_btn.config(state='normal')
        self.stop_detection_btn.config(state='disabled')
        self.color_info_label.config(text="检测已停止")
        self.detail_info_label.config(text="")
    
    def detection_loop(self):
        """检测循环"""
        if not self.detecting:
            return
        
        try:
            # 清除缓存确保实时检测
            if self.detector:
                self.detector.clear_cache()
                
                # 获取主要颜色
                dominant_color, confidence, detection_info = self.detector.get_dominant_color_at_center(use_cache=False)
                
                if dominant_color:
                    # 显示颜色信息
                    color_text = f"主要颜色: RGB{dominant_color} (置信度: {confidence:.3f})"
                    self.color_info_label.config(text=color_text)
                    
                    # 显示所有检测到的颜色
                    all_colors = detection_info.get('all_colors', [])
                    weights = detection_info.get('weights', [])
                    
                    if len(all_colors) > 1:
                        detail_text = "所有颜色: "
                        for i, (color, weight) in enumerate(zip(all_colors[:3], weights[:3])):
                            detail_text += f"RGB{color}({weight:.2f}) "
                        self.detail_info_label.config(text=detail_text)
                    else:
                        self.detail_info_label.config(text="单一颜色区域")
                else:
                    self.color_info_label.config(text="检测失败")
                    self.detail_info_label.config(text="")
        
        except Exception as e:
            self.color_info_label.config(text=f"检测错误: {e}")
            self.detail_info_label.config(text="")
        
        # 继续检测循环
        if self.detecting:
            self.root.after(100, self.detection_loop)  # 10Hz检测频率
    
    def run(self):
        """运行可视化工具"""
        self.root.mainloop()

def main():
    """主函数"""
    print("🔍 修复版颜色检测区域可视化工具")
    print("=" * 60)
    
    # 显示当前配置信息
    screen_width, screen_height = pyautogui.size()
    center_x, center_y = screen_width // 2, screen_height // 2
    
    print(f"屏幕信息:")
    print(f"  尺寸: {screen_width} x {screen_height} 像素")
    print(f"  中心点: ({center_x}, {center_y})")
    
    print(f"\n检测区域验证:")
    region_size = 200
    half_size = region_size // 2
    left = center_x - half_size
    top = center_y - half_size
    right = center_x + half_size
    bottom = center_y + half_size
    
    print(f"  设置: {region_size}x{region_size} 像素")
    print(f"  边界: ({left}, {top}) 到 ({right}, {bottom})")
    print(f"  宽度: {right - left} 像素")
    print(f"  高度: {bottom - top} 像素")
    print(f"  验证: {'✅ 正方形' if (right - left) == (bottom - top) == region_size else '❌ 非正方形'}")
    
    print(f"\n修复说明:")
    print("- 添加了无边框显示模式")
    print("- 添加了正方形验证功能")
    print("- 添加了网格和十字线辅助")
    print("- 修复了可能的显示问题")
    
    print(f"\n启动修复版可视化工具...")
    
    # 启动可视化工具
    visualizer = FixedDetectionAreaVisualizer()
    visualizer.run()

if __name__ == "__main__":
    main()
